package com.qiqidream.admin.security.login;

import com.alibaba.fastjson.JSON;
import com.qiqidream.admin.common.constant.StaticConstants;
import com.qiqidream.admin.common.response.ResponseCode;
import com.qiqidream.admin.common.response.ResponseResult;
import com.qiqidream.admin.common.utils.JwtUtil;
import com.qiqidream.admin.common.utils.ResponseUtil;
import com.qiqidream.admin.common.utils.UserAgentUtils;
import com.qiqidream.admin.security.entity.SecurityUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证成功处理
 * @author QiQiDream
 * @since 2019/11/18 9:58
 */
@Component
public class AdminAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    JwtUtil jwtUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication auth) {

        SecurityUser securityUser = ((SecurityUser) auth.getPrincipal());

        String deviceType = UserAgentUtils.getDeviceType(httpServletRequest).toLowerCase();
        // 生成jwt访问令牌,并返回给前端
        String jwt = jwtUtil.createJWT(securityUser.getCurrentUserInfo(),securityUser.getRoleCodes(),false,deviceType);
        Map<String,String> resultMap = new HashMap<>();
        resultMap.put(StaticConstants.TOKEN_HEADER,jwt);
        ResponseResult successResult = ResponseResult.success(ResponseCode.SUCCESS,resultMap);
        ResponseUtil.out(response, JSON.toJSONString(successResult));
    }

}
